<template>
  <GlobalDrawer
    v-model="visible"
    :title="formTitle"
    size="80%"
    :show-footer-buttons="true"
    @confirm="handleSubmit"
  >
    <el-form ref="formRef" :model="form" :rules="rules" label-width="100px" v-loading="loading">
      <el-form-item label="客户" prop="customer_id" v-if="!customerId">
        <el-select
          v-model="form.customer_id"
          placeholder="请选择客户"
          style="width: 100%"
          filterable
        >
          <el-option
            v-for="item in customerOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="联系人" prop="name">
        <el-input v-model="form.name" placeholder="请输入联系人姓名" />
      </el-form-item>

      <el-form-item label="职务" prop="position">
        <el-input v-model="form.position" placeholder="请输入职务" />
      </el-form-item>

      <el-form-item label="联系电话" prop="phone">
        <el-input v-model="form.phone" placeholder="请输入联系电话" />
      </el-form-item>

      <el-form-item label="微信号" prop="wechat">
        <el-input v-model="form.wechat" placeholder="请输入微信号" />
      </el-form-item>

      <el-form-item label="邮箱" prop="email">
        <el-input v-model="form.email" placeholder="请输入邮箱" />
      </el-form-item>

      <el-form-item label="主要联系人">
        <el-switch v-model="form.is_primary" :active-value="1" :inactive-value="0" />
      </el-form-item>
    </el-form>
  </GlobalDrawer>
</template>

<script setup lang="ts">
  import { ref, reactive, computed, watch } from 'vue'
  import { ElMessage } from 'element-plus'
  import request from '@/utils/request'
  import GlobalDrawer from '@/components/common/GlobalDrawer.vue'

  const props = defineProps({
    modelValue: {
      type: Boolean,
      default: false,
    },
    contactId: {
      type: Number,
      default: 0,
    },
    customerId: {
      type: Number,
      default: 0,
    },
  })

  const emit = defineEmits(['update:modelValue', 'success'])

  const visible = computed({
    get: () => props.modelValue,
    set: value => emit('update:modelValue', value),
  })

  const formRef = ref()
  const loading = ref(false)
  const submitting = ref(false)

  const form = reactive({
    customer_id: 0,
    name: '',
    position: '',
    phone: '',
    wechat: '',
    email: '',
    is_primary: 0,
  })

  const rules = {
    customer_id: [{ required: true, message: '请选择客户', trigger: 'change' }],
    name: [{ required: true, message: '请输入联系人姓名', trigger: 'blur' }],
    phone: [
      { required: true, message: '请输入联系电话', trigger: 'blur' },
      { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' },
    ],
  }

  const customerOptions = ref<Array<{ value: number; label: string }>>([])

  // 表单标题
  const formTitle = computed(() => {
    return props.contactId ? '编辑联系人' : '新增联系人'
  })

  // 获取客户选项
  const getCustomerOptions = async () => {
    try {
      const res = await request({
        url: '/api/crm/customer/list',
        method: 'get',
        params: { page: 1, limit: 1000 },
      })

      customerOptions.value = (res.data.list || []).map((item: any) => ({
        value: item.id,
        label: item.name,
      }))
    } catch (error: any) {
      // 忽略请求被取消的错误
      if (error?.code !== 'ERR_CANCELED') {
        console.error('获取客户列表失败:', error)
      }
    }
  }

  // 获取联系人详情
  const getContactDetail = async () => {
    if (!props.contactId) return

    loading.value = true
    try {
      const res = await request({
        url: '/api/crm/contact/detail',
        method: 'get',
        params: { id: props.contactId },
      })

      const data = res.data

      // 填充表单数据
      Object.keys(form).forEach(key => {
        if ((data as any)[key] !== undefined) {
          (form as any)[key] = (data as any)[key]
        }
      })
    } catch (error: any) {
      // 忽略请求被取消的错误（用户快速切换导致）
      if (error?.code !== 'ERR_CANCELED') {
        console.error('获取联系人详情失败:', error)
      }
    } finally {
      loading.value = false
    }
  }

  // 提交表单
  const handleSubmit = async () => {
    if (!formRef.value) return

    try {
      await formRef.value.validate()

      submitting.value = true

      const submitData = { ...form }

      // 如果传入了customerId，使用传入的customerId
      if (props.customerId) {
        submitData.customer_id = props.customerId
      }

      if (props.contactId) {
        // 编辑联系人
        await request({
          url: '/api/crm/contact/edit',
          method: 'put',
          data: { ...submitData, id: props.contactId },
        })
        ElMessage.success('修改申请已提交，等待管理员审核')
      } else {
        // 新增联系人
        await request({
          url: '/api/crm/contact/add',
          method: 'post',
          data: submitData,
        })
        ElMessage.success('新增成功')
      }

      emit('success')
      handleClose()
    } catch (error: any) {
      // 忽略请求被取消的错误
      if (error?.code !== 'ERR_CANCELED') {
        console.error('提交失败:', error)
      }
    } finally {
      submitting.value = false
    }
  }

  // 关闭对话框
  const handleClose = () => {
    // 重置表单
    if (formRef.value) {
      formRef.value.resetFields()
    }
    Object.keys(form).forEach(key => {
      if (key !== 'is_primary') {
        ;(form as any)[key] = key === 'customer_id' ? 0 : ''
      }
    })
    form.is_primary = 0

    visible.value = false
  }

  // 监听contactId变化
  watch(
    () => props.contactId,
    newVal => {
      if (newVal) {
        getContactDetail()
      }
    }
  )

  // 监听customerId变化
  watch(
    () => props.customerId,
    newVal => {
      if (newVal) {
        form.customer_id = newVal
      }
    }
  )

  // 监听对话框显示状态
  watch(visible, newVal => {
    if (newVal) {
      getCustomerOptions()
      if (props.contactId) {
        getContactDetail()
      } else if (props.customerId) {
        form.customer_id = props.customerId
      }
    }
  })
</script>

<style scoped>
  .el-form {
    padding-right: 20px;
  }
</style>
